#include "show_menulist.h"
#include "ui_show_menulist.h"
#include "bookstore.h"
#include "book.h"
#include <vector>
#include "utils.h"
using namespace utils;

show_menulist::show_menulist(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::show_menulist) {
    ui->setupUi(this);
}

show_menulist::~show_menulist() {
    delete ui;
}

void show_menulist::on_pushButton_clicked() {
    loadMenuList();
}

void show_menulist::loadMenuList() {
    auto size = sizeof (Menu);//学生类的大小
    FILE *file = openfile(menuDatPath, size); //打开文件

    fseek(file, 0, SEEK_END);//fseek将文件指针指到文件末尾
    auto offset = ftell(file);//ftell得到文件从指针到文件头的大小（offset是文件总大小）

    int row = offset / size; //采取和增加用户时算ID大小一样的方法算数据行数
    ui->tableWidget->setColumnCount(9); //设置列数
    QStringList header;
    header << "ID" << "ISBN" << "书名" << "作者" << "borrowCount" << "countNum" << "remain" << "reserveNum" << "exist";
    ui->tableWidget->setHorizontalHeaderLabels(header);
    ui->tableWidget->setRowCount(row);    //设置行数



    for(int i = 0; i < row; i++) {
        Menu* tempMenu = bookstore::createMenu();

        fseek(file, size * i, SEEK_SET);   //将指针移到该放的地方
        fread(tempMenu, size, 1, file);          //读出需要查询的同学数据

        QString ID = QString::number(tempMenu->ID);
        QString ISBN = QString(QString::fromLocal8Bit(tempMenu->ISBN, MAX_ISBN));
        QString name = QString(QString::fromLocal8Bit(tempMenu->name, MAX_BOOK_NAME));
        QString writer = QString(QString::fromLocal8Bit(tempMenu->writer, MAX_WRITER));
        QString borrowCount = QString::number(tempMenu->borrowCount);
        QString countNum = QString::number(tempMenu->countNum);
        QString remain = QString::number(tempMenu->remain);
        QString reserveNum = QString::number(tempMenu->reserveNum);
        QString exist = QString::number(tempMenu->exist);
        ui->tableWidget->setItem(i, 0, new QTableWidgetItem(ID));
        ui->tableWidget->setItem(i, 1, new QTableWidgetItem(ISBN));
        ui->tableWidget->setItem(i, 2, new QTableWidgetItem(name));
        ui->tableWidget->setItem(i, 3, new QTableWidgetItem(writer));
        ui->tableWidget->setItem(i, 4, new QTableWidgetItem(borrowCount));
        ui->tableWidget->setItem(i, 5, new QTableWidgetItem(countNum));
        ui->tableWidget->setItem(i, 6, new QTableWidgetItem(remain));
        ui->tableWidget->setItem(i, 7, new QTableWidgetItem(reserveNum));
        ui->tableWidget->setItem(i, 8, new QTableWidgetItem(exist));

        delete(tempMenu);
    }
    fclose(file);//关闭文件
}
